import 'package:floor/floor.dart';
import 'package:sqflite/sqflite.dart' as sqflite;
import 'dart:async';

part 'memo.g.dart';

class StringListConverter extends TypeConverter<List<String>, String> {
  @override
  List<String> decode(String databaseValue) {
    return databaseValue.isNotEmpty ? databaseValue.split('|') : [];
  }

  @override
  String encode(List<String> value) {
    return value.join('|');
  }
}

class DateTimeConverter extends TypeConverter<DateTime, int> {
  @override
  DateTime decode(int databaseValue) {
    return DateTime.fromMillisecondsSinceEpoch(databaseValue);
  }

  @override
  int encode(DateTime value) {
    return value.millisecondsSinceEpoch;
  }
}

@TypeConverters([StringListConverter, DateTimeConverter])
@Database(version: 2, entities: [Memo])
abstract class MemoDatabase extends FloorDatabase {
  MemoDao get memoDao;
}

@dao
abstract class MemoDao {
  @Query('SELECT * FROM Memo ORDER BY modified_time DESC')
  Future<List<Memo>> findAllMemos();

  @Query(
      'SELECT * FROM Memo WHERE title LIKE :searchKey OR content LIKE :searchKey ORDER BY modified_time DESC')
  Future<List<Memo>> findMemoWithSearchKey(String searchKey);

  @Query('SELECT * FROM Memo WHERE id = :id')
  Stream<Memo?> findMemoById(int id);

  @insert
  Future<void> insertMemo(Memo memo);

  @Update(onConflict: OnConflictStrategy.replace)
  Future<void> updateMemo(Memo memo);

  @delete
  Future<void> deleteMemo(Memo memo);
}

@entity
class Memo {
  @PrimaryKey(autoGenerate: true)
  final int? id;
  String title;
  String content;
  @ColumnInfo(name: 'created_time')
  DateTime createdTime;
  @ColumnInfo(name: 'modified_time')
  DateTime modifiedTime;
  String? category;
  List<String> tags;

  Memo({
    this.id,
    required this.title,
    required this.content,
    required this.createdTime,
    required this.modifiedTime,
    this.category = '',
    required this.tags,
  });
}
